package com.pdf;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author liyiruo
 * @Description
 * @Date 2021/8/10 下午4:44
 */
public class StamperPdf {
    public static void main(String[] args) throws IOException, DocumentException {
        //图片水印
        PdfReader reader = new PdfReader(DemoPDF.path + "ManyPagePDF.pdf");
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(DemoPDF.path
                + "StamperPdf.pdf"));

        Image img = Image.getInstance(DemoPDF.basePath+"imgData/水印.jpeg");
        img.setAbsolutePosition(200, 400);
        PdfContentByte under = stamp.getUnderContent(1);
        under.addImage(img);

        //文字水印
        PdfContentByte over = stamp.getOverContent(2);
        over.beginText();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
                BaseFont.EMBEDDED);
        over.setFontAndSize(bf, 18);
        over.setTextMatrix(30, 30);
        over.showTextAligned(Element.ALIGN_LEFT, "this is StamperPdf", 230, 430, 45);
        over.showTextAligned(Element.ALIGN_LEFT, "this is StamperPdf", 100, 200, 45);
        over.showTextAligned(Element.ALIGN_LEFT, "this is StamperPdf", 400, 100, 45);
        over.endText();

        //背景图
        Image img2 = Image.getInstance(DemoPDF.basePath+"imgData/背景图.jpg");
        img2.setAbsolutePosition(0, 0);
        PdfContentByte under2 = stamp.getUnderContent(3);
        under2.addImage(img2);

        stamp.close();
        reader.close();
    }
}
